package com.hngy.educationaladministration.config;

/**
 * @Author: Deng JunHao
 * @Date: 2021-05-03
 * @Description:
 */

import com.hngy.educationaladministration.utils.DateUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Title CosConfig
 * @Description 腾讯云上传文件cos
 * @Author
 * @Date 2021/3/2 11:48
 * @Version 1.0
 */
@Configuration
public class CosConfig {
    //cos配置参数
    private static String domain;

    private static String secretId;

    private static String secretKey;

    private static String bucketName;

    private static String region;

    //static 无法获取 value（）
    @Value("${cos.tencent.domain}")
    public void setDomain(String Domain) {
        domain = Domain;
    }

    @Value("${cos.tencent.secret-id}")
    public void setSecretId(String SecretId) {
        secretId = SecretId;
    }

    @Value("${cos.tencent.secret-key}")
    public void setSecretKey(String SecretKey) {
        secretKey = SecretKey;
    }


    @Value("${cos.tencent.bucket-name}")
    public void setBucketName(String BucketName) {
        bucketName = BucketName;
    }

    @Value("${cos.tencent.region}")
    public void setRegion(String Region) {
        region = Region;
    }

    // 腾讯云 自定义文件夹名称
    private static String PREFIX = "/test/";

    //设置文件夹名
    public static void setName(String changeName) {
        PREFIX = "/" + changeName + "/";
    }

    public static String uploadfile(MultipartFile file) {
        COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials, clientConfig);
        String fileName = file.getOriginalFilename();
        try {
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
            file.transferTo(localFile);
            Random random = new Random();
            fileName = PREFIX + random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, fileName, localFile);
            cosClient.putObject(objectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return domain + fileName;
    }

    /**
     * 下载url = 桶前缀+路径 -> domain+/+key
     *
     * @param id
     * @param name
     * @return
     */
    public static Map<String, Map<String, String>> getAllFileUrl(Long id, String name) {
        COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        setName(id.toString());
        Map<String, Map<String, String>> urls = new HashMap<>();
        COSClient cosClient = new COSClient(credentials, clientConfig);
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        // 设置bucket名称
        listObjectsRequest.setBucketName(bucketName);
        listObjectsRequest.setPrefix(PREFIX);
        listObjectsRequest.setDelimiter("/");
        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
        listObjectsRequest.setMaxKeys(1000);
        ObjectListing objectListing = null;
        do {
            try {
                objectListing = cosClient.listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
            } catch (CosClientException e) {
                e.printStackTrace();
            }
            // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
            List<String> commonPrefixs = objectListing.getCommonPrefixes();
            // object summary表示所有列出的object列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                HashMap<String, String> map = new HashMap<>();
                // 文件的路径key
                String key = cosObjectSummary.getKey();
                // 文件的etag
                String etag = cosObjectSummary.getETag();
                // 文件的长度
                long fileSize = cosObjectSummary.getSize();
                // 文件的存储类型
                String date = DateUtils.dateToDateTimeFormatter(cosObjectSummary.getLastModified());
                map.put(date, domain + "/" + key);
                urls.put(key, map);
            }
            String nextMarker = objectListing.getNextMarker();
            listObjectsRequest.setMarker(nextMarker);
        } while (objectListing.isTruncated());
        return urls;
    }

    /**
     * 查询存储桶列表
     *
     * @return
     */
    public static HashMap<String, String> getBuckets() {
        COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 创建 COS 客户端连接
        HashMap<String, String> res = new HashMap<>();
        COSClient cosClient = new COSClient(credentials, clientConfig);
        List<Bucket> buckets = cosClient.listBuckets();
        for (Bucket bucketElement : buckets) {
            String bucketName = bucketElement.getName();
            String bucketLocation = bucketElement.getLocation();
            res.put(bucketName, bucketLocation);
        }
        return res;
    }

    /**
     * fileName = folder/picture.jpg
     *
     * @param fileName
     * @return
     */
    public static void delFile(String fileName) {
        COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(credentials, clientConfig);
        cosClient.deleteObject(bucketName, fileName);
    }
}
